package com.central.modules.sys.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.common.utils.ConvertUtils;
import com.central.modules.sys.dao.SysRoleDao;
import com.central.modules.sys.entity.SysRoleEntity;
import com.central.modules.sys.model.AddSysRoleRequest;
import com.central.modules.sys.model.SysRoleQueryBean;
import com.central.modules.sys.service.SysRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRoleEntity> implements SysRoleService {
    @Override
    public IPage<SysRoleEntity> searchSysRoles(SysRoleQueryBean queryBean) {
        Page<SysRoleEntity> page = new Page<>(queryBean.getPageStart(), queryBean.getPageSize());
        LambdaQueryWrapper<SysRoleEntity> queryWrapper = new LambdaQueryWrapper<SysRoleEntity>();
        queryWrapper.orderByDesc(SysRoleEntity::getId);
        if (StringUtils.isNotBlank(queryBean.getName())) {
            queryWrapper.eq(SysRoleEntity::getName, queryBean.getName());
        }

        return this.page(page, queryWrapper);
    }

    @Override
    public SysRoleEntity addSysRole(AddSysRoleRequest request) {
        SysRoleEntity entity = ConvertUtils.sourceToTarget(request, SysRoleEntity.class);
        this.save(entity);
        return entity;
    }

    @Override
    public void deleteSysRole(Long id) {
        this.removeById(id);
    }

    @Override
    public boolean updateSysRole(Long id, AddSysRoleRequest request) {
        LambdaQueryWrapper<SysRoleEntity> queryWrapper = new LambdaQueryWrapper<SysRoleEntity>();
        queryWrapper.eq(SysRoleEntity::getId, id);
        SysRoleEntity sysRole = new SysRoleEntity();
        sysRole.setName(request.getName());
        sysRole.setRemark(request.getRemark());
        return this.update(sysRole, queryWrapper);
    }

    @Override
    public List<SysRoleEntity> findAll() {
        LambdaQueryWrapper<SysRoleEntity> queryWrapper = new LambdaQueryWrapper<SysRoleEntity>();
        queryWrapper.orderByDesc(SysRoleEntity::getCreateDate);
        return this.list(queryWrapper);
    }

    @Override
    public List<SysRoleEntity> findAllByIds(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<SysRoleEntity> queryWrapper = new LambdaQueryWrapper<SysRoleEntity>();
        queryWrapper.orderByDesc(SysRoleEntity::getId).in(SysRoleEntity::getId, ids);
        return this.list(queryWrapper);
    }
}
